<script setup lang="ts">
/**
 * 自定义上传图片组件。使用了@element-plus:2.8.8。
 *  注意：图片上传、下载和删除需要自己实现。
 *  @Author 游王子og
 *  @Date 2025/02/13
 *  @Version 1.0.0
 *
 *  prop:
 *    imageName:string = '': 图片名，用于回显图片
 *  emit:
 *    success: (imageName: string) => void: 图片上传成功回调，返回图片名
 */
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { deleteFileApi, downloadFileApi, uploadFileApi } from '@/assets/api/systemManagement/data/file'

// 图片名
const props = withDefaults(defineProps<{
  imageName?: string
}>(), {
  imageName: ''
})

// 上传成功回调方法，返回图片地址
const emit = defineEmits(['success'])

// 图片名
const imageName = ref(props.imageName)
// 图片地址 img标签src的值
const imageUrl = ref()

// 上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是jpg或png格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  uploadFileApi(rawFile, '').then((res) => {
    if (res.data.code === 200) {
      ElMessage.success('上传成功')
      imageName.value = res.data.data
      echoImage()
      emit('success', imageName.value)
    }
  })
  return false // 返回false，阻止默认上传行为
}

// 回显图片
const echoImage = () => {
  if (imageName.value != '') {
    downloadFileApi(imageName.value, 'image/png').then((res) => {
      imageUrl.value = URL.createObjectURL(res.data)
    })
  }
}

// 删除图片
const beforeRemove = () => {
  if (imageName.value != '') {
    deleteFileApi(imageName.value) // 调用服务器接口删除图片
  }
}

onMounted(() => {
  echoImage()
})
</script>

<template>
  <!-- 上传图片 -->
  <el-upload
    class="avatar-uploader"
    action="#"
    accept="image/*"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :before-remove="beforeRemove"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 250px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
